package com.cobra.mall.domain.goods.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cobra.mall.config.MallConst;
import com.cobra.mall.domain.goods.dao.GoodsMapper;
import com.cobra.mall.domain.goods.entity.GoodsEntity;
import com.cobra.mall.domain.goods.service.inter.GoodsService;
import com.cobra.mall.util.MallUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, GoodsEntity> implements GoodsService {
    @Autowired
    private StringRedisTemplate redisTemplate;



    @Override
    public GoodsEntity getByIdWithCache(Long goodsId) throws Exception {
        String json = redisTemplate.opsForValue().get(MallConst.GOODS_PREFIX + goodsId);
        if(json == null){
            GoodsEntity goodsEntity = getById(goodsId);
            redisTemplate.opsForValue().set(MallConst.GOODS_PREFIX + goodsId,MallUtil.fromObj2Json(goodsEntity),MallUtil.getRandom(200,500), TimeUnit.SECONDS);
            return goodsEntity;
        }else {
            return MallUtil.fromJson2Obj(json,GoodsEntity.class);
        }
    }
}
